/*
 * IntegrationHelper.java
 *
 * Copyright 2007, 2008 Tiberiumlabs
 *
 * This file is part of Tiberiumlabs Lailaps.
 *
 * Tiberiumlabs Lailaps is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Tiberiumlabs Lailaps is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tiberiumlabs.lailaps.settings.helpers;

import java.awt.Component;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JFileChooser;
import org.tiberiumlabs.lailaps.gui.elements.ExceptionDialog;
import org.tiberiumlabs.lailaps.settings.ApplicationSettings;
import org.tiberiumlabs.lailaps.settings.Settings;

/**
 *
 * @author <a href="mailto:paranoid.tiberiumlabs@gmail.com">Paranoid</a>
 */
public class IntegrationHelper {
    
    private static final ApplicationSettings APPLICATION_SETTINGS = Settings.getApplicationSettings();
    
    // <editor-fold defaultstate="collapsed" desc=" konqueror integration ">
    
    private static final String KONQUEROR_DOWNLOAD_MANAGER_PARAMETER = "DownloadManager=";
    private static final String KONQUEROR_BACKUP_FILE = APPLICATION_SETTINGS.LAILAPS_HOME + APPLICATION_SETTINGS.FILESEPARATOR + "konqueror-backup-line";
    private static final String KONQUEROR_EXECUTION_SCRIPT = APPLICATION_SETTINGS.LAILAPS_HOME + APPLICATION_SETTINGS.FILESEPARATOR + "lailaps-konqueror";
    
    public static void addKonqueror(Component parent) {
        
        try {
            
            
            JFileChooser fileChooser = new JFileChooser(APPLICATION_SETTINGS.LAILAPS_HOME);
            fileChooser.setDialogTitle("Choose Lailaps executable or main jar");
            fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            
            int res = fileChooser.showOpenDialog(parent);
            if (res == JFileChooser.APPROVE_OPTION) {
                
                // system:
                String lineSeparator = System.getProperty("line.separator");
                String fileSeparator = System.getProperty("file.separator");
                
                // <editor-fold defaultstate="collapsed" desc=" reading Konqueror config ">
                String konquerorConfigPath = System.getProperty("user.home") + fileSeparator + ".kde"
                        + fileSeparator + "share" + fileSeparator + "config" + fileSeparator + "konquerorrc";
                File konquerorConfigFile = new File(konquerorConfigPath);
                char[] konquerorConfigChars = new char[(int)konquerorConfigFile.length()];
                BufferedReader reader = new BufferedReader(new FileReader(konquerorConfigPath));
                int read = reader.read(konquerorConfigChars);
                reader.close();
                StringBuilder konquerorConfigBody = new StringBuilder();
                konquerorConfigBody.append(konquerorConfigChars, 0, read);
                // </editor-fold>
                
                // <editor-fold defaultstate="collapsed" desc=" downloadManager parameter ">
                int paramPosition = konquerorConfigBody.indexOf(KONQUEROR_DOWNLOAD_MANAGER_PARAMETER);
                int nextSeparator = 0;
                String backupString = ""; // TODO may be in future make null here
                if (paramPosition > 0) {
                    nextSeparator = konquerorConfigBody.indexOf(lineSeparator, paramPosition);
                    backupString = konquerorConfigBody.substring(paramPosition, nextSeparator);
                } else {
                    // TODO do something if there is no param
                }
                // </editor-fold>
                
                // <editor-fold defaultstate="collapsed" desc=" write backup file ">
                File backupFile = new File(KONQUEROR_BACKUP_FILE);
                BufferedWriter backupWriter = new BufferedWriter(new FileWriter(backupFile));
                backupWriter.write(backupString);
                backupWriter.flush();
                backupWriter.close();
                // </editor-fold>
                
                // string to file that will be executed:
                String executionString = null;
                
                // need to check if this is jar file or shell script:
                File selectedFile = fileChooser.getSelectedFile();
                String selectedFileName = selectedFile.getName();
                int dotPosition = selectedFileName.lastIndexOf('.');
                if (dotPosition > 0 && selectedFileName.substring(dotPosition+1).equals("jar")) {
                    
                    // <editor-fold defaultstate="collapsed" desc=" integrating jar file ">
                    
                    // <editor-fold defaultstate="collapsed" desc=" body of shell script ">
                    StringBuilder sb = new StringBuilder();
                    sb.append("#!/bin/sh");
                    sb.append(lineSeparator);
                    sb.append(System.getProperty("java.home"));
                    sb.append(fileSeparator);
                    sb.append("bin");
                    sb.append(fileSeparator);
                    sb.append("java -jar \"");
                    sb.append(selectedFile.getCanonicalPath());
                    sb.append("\" $*");
                    sb.append(lineSeparator);
                    // </editor-fold>
                    
                    // writing to file:
                    File runFile = new File(KONQUEROR_EXECUTION_SCRIPT);
                    BufferedWriter writer = new BufferedWriter(new FileWriter(runFile));
                    writer.write(sb.toString());
                    writer.flush();
                    writer.close();
                    runFile.setExecutable(true);
                    
                    // getting execution string:
                    executionString = runFile.getCanonicalPath();
                    
                    // </editor-fold>
                    
                } else {
                    
                    // <editor-fold defaultstate="collapsed" desc=" integrating executable or script ">
                    selectedFile.setExecutable(true);
                    executionString = selectedFile.getCanonicalPath();
                    // </editor-fold>
                }
                
                konquerorConfigBody.replace(paramPosition + KONQUEROR_DOWNLOAD_MANAGER_PARAMETER.length(), nextSeparator, executionString);
                BufferedWriter writer = new BufferedWriter(new FileWriter(konquerorConfigFile));
                writer.write(konquerorConfigBody.toString());
                writer.flush();
                writer.close();
                
            }
        } catch (Exception e) {
            new ExceptionDialog(e);
        }
        
    }
    
    public static void removeKonqueror() {
        try {
            
            // system:
            String lineSeparator = System.getProperty("line.separator");
            String fileSeparator = System.getProperty("file.separator");
            
            String backupString = null;
            
            // <editor-fold defaultstate="collapsed" desc=" reading backup file to read backuped string ">
            File backupFile = new File(KONQUEROR_BACKUP_FILE);
            if (backupFile.exists()) {
                BufferedReader reader = new BufferedReader(new FileReader(backupFile));
                char[] backupContent = new char[(int)backupFile.length()];
                int read = reader.read(backupContent);
                reader.close();
                
                backupString = new String(backupContent, 0, read);
            }
            if (backupString == null || backupString.isEmpty()) {
                backupString = KONQUEROR_DOWNLOAD_MANAGER_PARAMETER;
            }
            // </editor-fold>
            
            // <editor-fold defaultstate="collapsed" desc=" reading konqueror configuration ">
            String konquerorConfigPath = System.getProperty("user.home") + fileSeparator + ".kde"
                    + fileSeparator + "share" + fileSeparator + "config" + fileSeparator + "konquerorrc";
            File konquerorConfigFile = new File(konquerorConfigPath);
            char[] konquerorConfigChars = new char[(int)konquerorConfigFile.length()];
            BufferedReader reader = new BufferedReader(new FileReader(konquerorConfigPath));
            int read = reader.read(konquerorConfigChars);
            reader.close();
            StringBuilder konquerorConfigBody = new StringBuilder();
            konquerorConfigBody.append(konquerorConfigChars, 0, read);
            // </editor-fold>
            
            // <editor-fold defaultstate="collapsed" desc=" downloadManager parameter ">
            int paramPosition = konquerorConfigBody.indexOf(KONQUEROR_DOWNLOAD_MANAGER_PARAMETER);
            int nextSeparator = 0;
            if (paramPosition > 0) {
                nextSeparator = konquerorConfigBody.indexOf(lineSeparator, paramPosition);
            } else {
                // TODO do something if there is no param
            }
            // </editor-fold>
            
            konquerorConfigBody.replace(paramPosition, nextSeparator, backupString);
            
            BufferedWriter writer = new BufferedWriter(new FileWriter(konquerorConfigFile));
            writer.write(konquerorConfigBody.toString());
            writer.flush();
            writer.close();
            
        } catch (Exception ex) {
            new ExceptionDialog(ex);
        }
    }
    
    // </editor-fold>
    
}
